﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Threading;
using System.Drawing;
using System.IO;
using System.Collections.Specialized;
using System.Xml.Linq;

namespace GiMess
{
    public static class AvatarDownloader
    {
        private static WebClient webClient;
        private static Thread workerThread;
        private static bool working;

        private static volatile Queue<string> downloadQueue;
        private static volatile Queue<string> imageKeyQueue;

        private static string  leftUrl = "http://i.imgur.com/";
        private static string rightUrl = "s.png";

        public static int Counter = 2;

        public static void Init()
        {
            downloadQueue = new Queue<string>();
            imageKeyQueue = new Queue<string>();
            webClient     = new WebClient();
            //workerThread  = new Thread(new ThreadStart(Work));
            working = false;
            
        }

        public static void SetOwnAvatar(string url)
        {
            HttpWebRequest  request;
            WebResponse     response;

            if (url == "") return;

            url = leftUrl + url + rightUrl;
            request = (HttpWebRequest)WebRequest.Create(url);
            request.AllowAutoRedirect = false;

            response = request.GetResponse();

            Image image = new Bitmap(response.GetResponseStream());
            FormsManager.MainForm.SetOwnAvatar(image);
        }

        //deprecated
        public static void SetOwnAvatar2(string url)
        {
            url = leftUrl + url + rightUrl;
            byte[] imageData = webClient.DownloadData(url);
            Image image = new Bitmap(new MemoryStream(imageData));

            image.Save("debugimage.jpg");

            FormsManager.MainForm.SetOwnAvatar(image);
        }

        public static void AddToQueue(string key, string url)
        {
            lock (downloadQueue) lock(imageKeyQueue)
            {
                downloadQueue.Enqueue(url);
                imageKeyQueue.Enqueue(key);
            }

            if (!working)
            {
                working = true;
                workerThread = new Thread(new ThreadStart(Work));
                workerThread.Start();
            }
        }

        private static void Work()
        {
            while (downloadQueue.Count > 0)
                DownloadNewItem();
            working = false;
            FormsManager.MainForm.ListInvokeInvalidate();
        }

        private static void DownloadNewItem()
        {
            string imageUrl;
            string imageKey;
            lock (downloadQueue) lock(imageKeyQueue) //trebuie si aici lock? nu cred
            {
                imageUrl = leftUrl + downloadQueue.Dequeue() + rightUrl;
                imageKey = imageKeyQueue.Dequeue();
            }

            HttpWebRequest request;
            WebResponse    response;

            request = (HttpWebRequest)WebRequest.Create(imageUrl);
            request.AllowAutoRedirect = false;
            
            try
            {
                response = request.GetResponse();
                Image image = new Bitmap(response.GetResponseStream());
                FormsManager.MainForm.ListInvokeAddAvatar(imageKey, image);
            }
            catch
            { }
        }
    }

    public static class AvatarUploader
    {
        private static WebClient webClient;
        private static Thread workerThread;

        private static string path;
        private static bool working;

        public static void Init()
        {
            webClient    = new WebClient();
            workerThread = new Thread(new ThreadStart(Work));
            
            path = "";  working = false;
        }

        public static void SetAvatar(string filePath)
        {
            path = filePath;
            if (!working)
            {
                working = true;
                workerThread = new Thread(new ThreadStart(Work));
                workerThread.Start();
            }
        }

        private static void Work()
        {
            var values = new NameValueCollection
            {
                { "key", "d4d0f4c31e9b670508bc3918c6c05e91" },
                { "image", Convert.ToBase64String(File.ReadAllBytes(path)) }
            };
            
            byte[] responseData = webClient.UploadValues("http://imgur.com/api/upload.xml", values);

            XDocument response = XDocument.Load(new MemoryStream(responseData));
            XObject node = response.Root.FirstNode;

            string hash = node.ToString();

            hash = hash.Replace("<image_hash>", "");
            hash = hash.Replace("</image_hash>", "");

            GiNetClient.Instance.UpdateAvatar(hash);
            AvatarDownloader.SetOwnAvatar(hash);
            working = false;
        }
    }
}
